<template>
  <section>
    <resource v-if="board.menuId"
              :menu-id="board.menuId"
              @input="handleResources" />
    <FormProvider :value="formData"
                  :entries="formEntries"
                  :actions="formActions"
                  :rules="formRules"
                  @input="handleInput"
                  @submit="handleSubmit" />
  </section>
</template>

<script>
import Vue from "vue";
import { mapActions, mapState } from "vuex";
import { FormProvider } from "@formla";
import Resource from "@menu/Resource.vue";
import BasicComponents from "@/components/basic";

Vue.use(BasicComponents)

export default {
  name: "FormBoard",
  components: { FormProvider, Resource },
  props: {
    board: Object
  },
  data () {
    return {
      submitData: {},
      resources: []
    };
  },
  computed: {
    ...mapState({
      formData: (state) => state.form.data,
      formRules: (state) => state.form.rules,
      formEntries: (state) => state.form.entries,
      formActions: (state) => state.form.actions
    }),
    formResource () {
      return this.resources.filter(
        (resource) => resource.resourceId == this.board.resourceId
      )?.[0];
    }
  },
  methods: {
    ...mapActions({
      initialize: "form/initialize",
      submit: "form/submit"
    }),
    handleInput (data) {
      this.submitData = data;
    },
    handleResources (resources = []) {
      this.resources = resources;
      this.initialize({ resource: this.formResource, board: this.board });
    },
    async handleSubmit (action) {
      let response = await this.submit(this.submitData);
      if (response.code === 0) {
        this.$message({ type: "success", message: "保存成功" });
        this.$emit("submit", action);
        this.$router.back();
      } else {
        const { message = "保存失败" } = response;
        this.$message({ type: "error", message });
      }
    }
  }
};
</script>
